import { Modal } from 'ant-design-vue';
import call from '../assets/call.wav';

export default class RemindAudio {
  constructor(options) {
    options = Object.assign(
      {
        frequency: 3,
      },
      options,
    );
    let audio = document.createElement('audio');
    let ready = new Promise((resolve) => {
      audio.oncanplay = function () {
        resolve();
      };
    });
    audio.src = call;
    async function popup() {
      return await new Promise((resolve) => {
        if (document.USER_CLICK_HANDLED === true) {
          return resolve();
        }
        Modal.info({
          title: '您有未签收指令！',
          content: '当前提示后续不会出现，请打开音量注意提示音！',
          afterClose: () => {
            document.USER_CLICK_HANDLED = true;
            resolve();
          },
        });
      });
    }
    async function play() {
      let frequency = options.frequency;
      audio.onended = function () {
        if (--frequency > 0) {
          audio.play();
        } else {
          audio.onended = null;
          frequency = null;
        }
      };
      await ready;
      await popup();
      await audio.play();
    }
    function pause() {
      audio.pause();
    }
    function destroy() {
      pause();
      ready = null;
      audio = null;
    }
    return {
      play,
      pause,
      destroy,
    };
  }
}
